<template>
  <NDrawer v-model:show="visible" :title="title" display-directive="show" :width="360">
    <NDrawerContent :title="title" :native-scrollbar="false" closable>
      <NForm ref="formRef" :model="model" :rules="rules">
        <NFormItem label="i18nKey" path="i18nKey">
          <NInput v-model:value="model.meta.i18nKey"/>
        </NFormItem>
        <NFormItem label="图标" path="icon">
          <NInput v-model:value="model.meta.icon"/>
        </NFormItem>
        <NFormItem label="title" path="title">
          <NInput v-model:value="model.meta.title"/>
        </NFormItem>
      </NForm>
      <template #footer>
        <NSpace :size="16">
          <NButton @click="closeDrawer">{{ $t('common.cancel') }}</NButton>
          <NButton type="primary" @click="handleSubmit">{{ $t('common.confirm') }}</NButton>
        </NSpace>
      </template>
    </NDrawerContent>
  </NDrawer>
</template>
<script setup lang="ts">
  import {$t} from "@/locales";
  import {reactive, ref, watch} from "vue";
  import {fetchUpdateMenu} from "@/service/api";
  import {useFormRules, useNaiveForm} from "@/hooks/common/form";

  const {formRef, validate, restoreValidation} = useNaiveForm();
  const {defaultRequiredRule} = useFormRules();
  const model: Api.SystemManage.Menu = reactive({
    name: '',
    component: '',
    path: '',
    order: 0,
    meta: {
      i18nKey: '',
      icon: '',
      title: ''
    }
  });

  defineOptions({
    name: 'MenuEdit'
  });

  interface Props {
    rowData?: Api.SystemManage.Menu | null;
  }

  interface Emits {
    (e: 'submitted'): void;
  }

  const title = ref<string>('修改菜单');
  const visible = defineModel<boolean>('visible', {
    default: false
  });
  const props = defineProps<Props>();

  const rules: Record<keyof Pick<Api.SystemManage.Meta, 'icon' | 'title' | 'i18nKey'>, App.Global.FormRule> = {
    icon: defaultRequiredRule,
    title: defaultRequiredRule,
    i18nKey: defaultRequiredRule
  };
  const emit = defineEmits<Emits>();

  function closeDrawer() {
    visible.value = false;
  }

  async function handleSubmit() {
    await validate();
    let {error} = await fetchUpdateMenu(model);
    if (!error) {
      window.$message?.success($t('common.updateSuccess'));
      closeDrawer();
      emit('submitted');
    }
  }

  watch(visible, () => {
    if (visible.value) {
      if (props.rowData) {
        Object.assign(model, props.rowData);
      }
      restoreValidation();
    }
  });
</script>
<style scoped>

</style>
